import { useState, useEffect } from 'react';
import { getRole, updateRole, addRole } from '@/mocks/roles';
import { useNavigate, useParams } from 'react-router-dom';

interface RoleFormProps {
  // 这是角色添加/编辑表单，将在后续步骤中完善实现
}

export default function RoleForm() {
  const { id } = useParams();
  const navigate = useNavigate();
  const [isEditing, setIsEditing] = useState(!!id);
  const [formData, setFormData] = useState({
    name: '',
    description: '',
    personality: '',
    image: '',
    abilities: [''],
    isDefault: false,
    background: ''
  });

  useEffect(() => {
    if (isEditing && id) {
      // 加载要编辑的角色数据
      const roleId = parseInt(id);
      const roleData = getRole(roleId);
      
      if (roleData) {
        setFormData({
          name: roleData.name || '',
          description: roleData.description || '',
          personality: roleData.personality || '',
          image: roleData.image || '',
          abilities: roleData.abilities?.length ? [...roleData.abilities] : [''],
          isDefault: roleData.isDefault || false,
          background: roleData.background || ''
        });
      } else {
        // 如果找不到角色，重定向到角色列表
        navigate('/roles');
      }
    }
  }, [isEditing, id, navigate]);

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };
  
  const handleAbilityChange = (index: number, value: string) => {
    const newAbilities = [...formData.abilities];
    newAbilities[index] = value;
    setFormData(prev => ({ ...prev, abilities: newAbilities }));
  };
  
  const addAbilityField = () => {
    setFormData(prev => ({ 
      ...prev, 
      abilities: [...prev.abilities, ''] 
    }));
  };
  
  useEffect(() => {
    if (isEditing) {
      // 在实际实现中，这里会加载要编辑的角色数据
      setFormData({
        name: '加载中...',
        description: '加载中...',
        personality: '加载中...',
        image: '',
        abilities: [''],
        isDefault: false
      });
    }
  }, [isEditing]);
  
  const handleSubmit = (e: React.FormEvent) => {
    e.preventDefault();
    
    // 基本表单验证
    if (!formData.name || !formData.description || !formData.personality) {
      alert('请填写必填字段');
      return;
    }
    
    // 处理能力数组，过滤空值
    const abilities = formData.abilities.filter(ability => ability.trim() !== '');
    if (abilities.length === 0) {
      alert('请至少添加一项能力');
      return;
    }
    
    const roleData = {
      ...formData,
      abilities,
      // 如果是编辑，保留原id
      id: isEditing ? parseInt(id!) : undefined
    };
    
    try {
      if (isEditing) {
        updateRole(roleData);
        alert('角色更新成功');
      } else {
        addRole(roleData);
        alert('角色创建成功');
      }
      navigate('/roles');
    } catch (error) {
      console.error('保存角色失败', error);
      alert('保存角色失败，请重试');
    }
  };
  
  return (
    <div className="max-w-2xl mx-auto bg-white rounded-2xl shadow-lg p-8">
      <h2 className="text-2xl font-bold text-gray-800 mb-6">{isEditing ? '编辑角色' : '新增角色'}</h2>
      
      <form onSubmit={handleSubmit} className="space-y-6">
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div className="md:col-span-2">
            <label htmlFor="name" className="block text-sm font-medium text-gray-700 mb-1">角色名称</label>
            <input
              type="text"
              id="name"
              name="name"
              value={formData.name}
              onChange={handleInputChange}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="description" className="block text-sm font-medium text-gray-700 mb-1">角色描述</label>
            <textarea
              id="description"
              name="description"
              value={formData.description}
              onChange={handleInputChange}
              rows={3}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            ></textarea>
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="personality" className="block text-sm font-medium text-gray-700 mb-1">性格特点</label>
            <input
              type="text"
              id="personality"
              name="personality"
              value={formData.personality}
              onChange={handleInputChange}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
              required
            />
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="background" className="block text-sm font-medium text-gray-700 mb-1">背景故事</label>
            <textarea
              id="background"
              name="background"
              value={formData.background}
              onChange={handleInputChange}
              rows={4}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
            ></textarea>
          </div>
          
          <div className="md:col-span-2">
            <label htmlFor="image" className="block text-sm font-medium text-gray-700 mb-1">角色图片URL</label>
            <input
              type="text"
              id="image"
              name="image"
              value={formData.image}
              onChange={handleInputChange}
              className="w-full px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
            />
          </div>
          
          <div className="md:col-span-2">
            <label className="block text-sm font-medium text-gray-700 mb-3">能力</label>
            {formData.abilities.map((ability, index) => (
              <div key={index} className="flex gap-2 mb-2">
                <input
                  type="text"
                  value={ability}
                  onChange={(e) => handleAbilityChange(index, e.target.value)}
                  className="flex-grow px-4 py-3 rounded-xl border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500"
                  placeholder={`能力 ${index + 1}`}
                />
                <button
                  type="button"
                  className="px-3 py-3 bg-gray-100 text-gray-600 rounded-xl hover:bg-gray-200 transition-colors"
                  onClick={() => {
                    if (formData.abilities.length > 1) {
                      const newAbilities = formData.abilities.filter((_, i) => i !== index);
                      setFormData(prev => ({ ...prev, abilities: newAbilities }));
                    }
                  }}
                >
                  <i className="fa-solid fa-trash"></i>
                </button>
              </div>
            ))}
            <button
              type="button"
              className="mt-2 px-4 py-2 bg-blue-100 text-blue-600 rounded-xl hover:bg-blue-200 transition-colors text-sm"
              onClick={() => {
                setFormData(prev => ({ ...prev, abilities: [...prev.abilities, ''] }));
              }}
            >
              <i className="fa-solid fa-plus mr-1"></i> 添加能力
            </button>
          </div>
          
          <div className="md:col-span-2 flex items-center">
            <input
              type="checkbox"
              id="isDefault"
              checked={formData.isDefault}
              onChange={(e) => setFormData(prev => ({ ...prev, isDefault: e.target.checked }))}
              className="w-4 h-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
            />
            <label htmlFor="isDefault" className="ml-2 block text-sm text-gray-700">设为默认角色</label>
          </div>
        </div>
        
        <div className="flex justify-end gap-4 pt-4 border-t border-gray-100">
          <button
            type="button"
            className="px-6 py-3 border border-gray-300 text-gray-700 rounded-xl hover:bg-gray-50 transition-colors"
            onClick={() => navigate('/roles')}
          >
            取消
          </button>
          <button
            type="submit"
            className="px-6 py-3 bg-blue-600 text-white rounded-xl hover:bg-blue-700 transition-colors"
          >
            {isEditing ? '更新角色' : '创建角色'}
          </button>
        </div>
      </form>
    </div>
  );
}